import { useParams } from 'react-router-dom';
import styles from './index.module.scss';
import Icon from '@/components/Icon';
import NavBar from '@/components/NavBar';
import {
  ClearDetailAction,
  GetArticleDetailById,
  isFollowingsAction,
} from '@/store/action/articles';
import classnames from 'classnames';
import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useAppSelector } from '@/store';
import DOMPurify from 'dompurify';
import dayjs from 'dayjs';
import Skeleton from '@/components/Skeleton';
import hljs from 'highlight.js';
import NoComment from './components/NoComment';
import CommentItem from './components/CommentItem';
// 可以去项目下找到各种各样的主题风格
// import 'highlight.js/styles/vs2015.css';
import 'highlight.js/styles/github-dark.css';
import {
  ClearCommentAction,
  getCommentsByIdAction,
} from '@/store/action/comment';
import CommentFooter from './components/CommentFooter';
import { Popup, Toast } from 'antd-mobile';
import CommentReply from './components/CommentReply';
type DetailArticleType = {
  article_id: string;
};

export default function Article() {
  const params = useParams() as DetailArticleType;
  const wrapRef = useRef<HTMLDivElement>(null);
  // 1.  声明ref 绑定ref，保存作者信息的DOM
  const authRef = useRef<HTMLDivElement>(null);
  const [navAuthShow, setNavAuthShow] = useState(false);

  const {
    originComment,
    commentInfo: { results: commentlist },
  } = useAppSelector((state) => state.comment);
  const scrollFn = () => {
    const top = authRef.current!.getBoundingClientRect().top;

    if (top < 10) {
      // 如果top<10 表示看不见原本的作者信息
      setNavAuthShow(true);
    } else {
      setNavAuthShow(false);
    }
    // TODO: 改变state即可
  };

  const { article_id } = params;
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(GetArticleDetailById(article_id));
    const WrapDom = wrapRef.current!; // eslint-disable-next-line
    return () => {
      dispatch(ClearDetailAction());
      if (!ArtcleDetail.title) return;
      WrapDom.removeEventListener('scroll', scrollFn);
    };
    // eslint-disable-next-line
  }, [article_id, dispatch]);

  // 💥3. 挂载后获取文章的评论
  useEffect(() => {
    dispatch(getCommentsByIdAction({ type: 'a', source: article_id }));
    return () => {
      dispatch(ClearCommentAction());
    };
  }, [article_id, dispatch]);

  const { ArtcleDetail } = useAppSelector((state) => state.articles);
  useEffect(() => {
    wrapRef.current?.addEventListener('scroll', scrollFn);
    // 配置 highlight.js
    hljs.configure({
      // 忽略未经转义的 HTML 字符
      ignoreUnescapedHTML: true,
    });

    // 查找容器元素下符合 pre code 选择器规则的子元素，进行高亮
    const codes = document.querySelectorAll('.dg-html pre code');
    if (codes.length > 0) {
      return codes.forEach((el) => hljs.highlightElement(el as any));
    }

    const pre = document.querySelectorAll('.dg-html pre');
    if (pre.length > 0) {
      pre.forEach((el) => hljs.highlightElement(el as any));
    }
  }, [ArtcleDetail.title]);

  /** 关注用户 */
  const handleis_followed = async () => {
    await dispatch(
      isFollowingsAction(ArtcleDetail.aut_id, ArtcleDetail.is_followed)
    );
    Toast.show({
      icon: 'success',
      content: ArtcleDetail.is_followed ? '取消关注成功' : '关注成功',
    });
  };

  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        {/* 顶部导航栏 */}
        <NavBar right={<Icon type="icongengduo" />}>
          {/* 1. 准备静态结构 */}
          {navAuthShow && (
            <div className="nav-author">
              <img src={ArtcleDetail.aut_photo} alt="" />
              <span className="name">{ArtcleDetail.aut_name}</span>
              <span
                onClick={() => handleis_followed()}
                className={classnames(
                  'follow',
                  ArtcleDetail.is_followed ? 'followed' : ''
                )}
              >
                {ArtcleDetail.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          )}
        </NavBar>
        {!ArtcleDetail.title ? (
          <Skeleton></Skeleton>
        ) : (
          <div className="wrapper" ref={wrapRef}>
            <div className="article-wrapper">
              {/* 文章描述信息栏 */}
              <div className="header">
                <h1 className="title">{ArtcleDetail.title}</h1>

                <div className="info">
                  <span>{dayjs().from(ArtcleDetail.pubdate)}</span>
                  <span>{ArtcleDetail.read_count} 阅读</span>
                  <span>{ArtcleDetail.comm_count} 评论</span>
                </div>

                <div className="author" ref={authRef}>
                  <img src={ArtcleDetail.aut_photo} alt="" />
                  <span className="name">{ArtcleDetail.aut_name}</span>
                  <span
                    onClick={() => handleis_followed()}
                    className={classnames(
                      'followbtn',
                      ArtcleDetail.is_followed ? 'followed' : 'follow'
                    )}
                  >
                    {ArtcleDetail.is_followed ? '已关注' : '关注'}
                  </span>
                </div>
              </div>

              {/* 文章正文内容区域 */}
              <div className="content">
                <div
                  className="content-html dg-html"
                  dangerouslySetInnerHTML={{
                    __html: DOMPurify.sanitize(ArtcleDetail.content),
                  }}
                ></div>
                <div className="date">
                  发布文章时间：
                  {dayjs(ArtcleDetail.pubdate).format('YYYY年MM月DD日')}
                </div>
                {/* 💥 静态结构和date 同级 */}
                <div className="divider"></div>
                <div className="comment">
                  {/* 评论总览信息 */}
                  <div className="comment-header">
                    <span>全部评论（{ArtcleDetail.comm_count}）</span>
                    <span>{ArtcleDetail.like_count} 点赞</span>
                  </div>
                  {/* 评论列表 */}
                  {ArtcleDetail.comm_count === 0 ? (
                    <NoComment />
                  ) : (
                    <div className="comment-list">
                      {commentlist.map((item) => {
                        return <CommentItem comment={item} key={item.com_id} />;
                      })}
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        )}

        <CommentFooter />
        <Popup
          visible={!!originComment.com_id}
          position="right"
          bodyStyle={{ minWidth: '100vw' }}
        >
          <CommentReply></CommentReply>
        </Popup>
      </div>
    </div>
  );
}
